package com.paipai.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.paipai.dao.AddressMapper;
import com.paipai.entity.Address;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;


@Transactional
@Service
public class AddressService {
	@Autowired
	private AddressMapper addressMapper;

	public AddressMapper getAddressMapper() {
		return addressMapper;
	}
	/**
	 * 查询用户收货地址
	 * @param uid
	 * @return
	 */
	public List<Address> findAddress(int uid) {
		
		
		Example exm = new Example(Address.class);
		
		Criteria crt = exm.createCriteria();
		
		//查询数据列表
		if (!"".equals(uid)) {
			crt.andCondition("user_id=", uid);
		}
		
		List<Address> list = addressMapper.selectByExample(exm);
		
		return list;
	}
	
	
	
	/**
	 * 新增地址
	 * @param address
	 * @return
	 */
	public Integer insertAddress(Address address) {
		//如果新添加的地址设置为1 默认地址,则把该用户其他地址全部设为0普通地址
		if(address.getDefaultadd()==1) {
			
			Integer row1 = addressMapper.updateDefaultadd(address.getUserId());
			
			//if(row1==0||row1==null) return 0;
		}
		
		//新增一条地址
		return addressMapper.insert(address);
	}
	
	/**
	 * 修改地址 显示信息默认地址
	 * @param id
	 * @return
	 */
	public Address findAddressById(Integer id) {
		
		return addressMapper.selectByPrimaryKey(id);
	}
	
	
	
	
	/**
	 * 新增地址
	 * @param address
	 * @return
	 */
	public Integer updatatAddressById(Address address) {
		//如果修改地址设置为1 默认地址,则把该用户其他地址全部设为0普通地址
		if(address.getDefaultadd()==1) {
			Integer row1 = addressMapper.updateDefaultadd(address.getUserId());
			
			//if(row1==0||row1==null) return 0;
		}
		
		//根据id更新地址
		return addressMapper.updateByPrimaryKeySelective(address);
	}
	
	
	/**
	 * 删除 地址
	 * @param id
	 * @return
	 */
	public Integer deleteaddressById(Integer id) {
		
		return addressMapper.deleteByPrimaryKey(id);
	}
	
	
	/**
	 * 定时任务
	 * @param userId
	 * @return
	 */
	public Address findDefaultAddressByUserId(Integer userId) {
		return addressMapper.findDefaultAddressByUserId(userId);
	}

}